package com.lqjava.flowable.serverapp.app.ws;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.lqjava.flowable.beans.enums.WebSocketJSMethods;
import com.lqjava.flowable.beans.result.ResultBean;
import com.lqjava.flowable.serverapp.sys.config.websocket.WebSocketMSGContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket 登录接口
 * 记录登录客户端
 * @author lq 2021年3月21日 19:05:28
 */
@Slf4j
@ServerEndpoint("/ws/login/{clientid}")
@Component
public class LoginWebSocketServer {
	private Session session;
	private Long accountid;
	private String uuid;
	private static ConcurrentHashMap<Long, Map<String,LoginWebSocketServer>> BASE_MAP = new ConcurrentHashMap<>();

	//允许多端登录
	@OnOpen
	public void onOpen(Session session, @PathParam("accountid") Long accountid) {

		this.session = session;
		this.accountid = accountid;
		this.uuid = IdUtil.fastSimpleUUID();

		log.info("[连接成功] {}:{}",this.accountid,this.uuid);

		Map<String,LoginWebSocketServer> socketMap = BASE_MAP.get(this.accountid);
		if(socketMap == null) socketMap = new ConcurrentHashMap<>();BASE_MAP.put(this.accountid, socketMap);
		socketMap.put(uuid, this);

		Map<String,String> params = new HashMap<>();
		params.put("uuid", this.uuid);
		sendMessage(ResultBean.result4Object(new WebSocketMSGContent(WebSocketJSMethods.LOGIN_SUCCESS, this.accountid, params)));
	}

	@OnClose
	public void onClose() {
		Map<String, LoginWebSocketServer> socketMap = BASE_MAP.get(this.accountid);
		if(socketMap != null && socketMap.containsKey(this.uuid)){
			log.info("[连接关闭] {}:{}",this.accountid,this.uuid);
			socketMap.remove(this.uuid);
		}
	}

	@OnMessage
	public void onMessage(String message, Session session) {
		try {
			sendMessage(ResultBean.result4String(IdUtil.fastSimpleUUID()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		log.error("[连接异常] {}:{} 原因:{}",this.accountid,this.uuid,error.getMessage());
		error.printStackTrace();
	}


	public void sendMessage(Object content){
		String string = JSON.toJSONString(content);
		sendMessage(string);
	}

	public void sendMessage(String string){
		try {
			log.info("[发送消息] {}:{} 消息:{}",this.accountid,this.uuid,string);
			this.session.getBasicRemote().sendText(string);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void sendInfo(Object content,Long accountid){
		String string = JSON.toJSONString(content);
		Map<String, LoginWebSocketServer> socketMap = BASE_MAP.get(accountid);
		log.info("[指定消息] {}:{} 消息:{}",accountid,socketMap.keySet(),string);
		socketMap.entrySet().forEach(e -> e.getValue().sendMessage(string));
	}

	public static void sendInfo(Object content){
		String string = JSON.toJSONString(content);
		log.info("[群发消息] {}",content);
		BASE_MAP.entrySet().forEach(e -> e.getValue().entrySet().forEach(e2 -> e2.getValue().sendMessage(content)));
	}

	
}
